<template>
  <el-dialog
      v-model="visible"
      title="选择训练分类"
      width="600px"
      @close="handleClose"
  >
    <div class="category-selector">
      <div class="selector-section">
        <div class="section-title">选择分类</div>

        <!-- 分类选择 -->
        <div class="category-tree">
          <!-- 一级分类 -->
          <div class="tree-level">
            <div class="level-title">一级分类</div>
            <div class="level-items">
              <div
                  v-for="category in categories.primary"
                  :key="category.id"
                  class="category-item"
                  :class="{ active: selected.primary === category.id }"
                  @click="selectCategory('primary', category.id)"
              >
                {{ category.name }}
                <el-icon
                    class="delete-icon"
                    @click.stop="deleteCategory('primary', category.id)"
                >
                  <Delete />
                </el-icon>
              </div>
              <div class="category-item add-new" @click="showAddDialog('primary')">
                <el-icon><Plus /></el-icon>
                添加分类
              </div>
            </div>
          </div>

          <!-- 二级分类 -->
          <div class="tree-level" v-if="selected.primary">
            <div class="level-title">二级分类</div>
            <div class="level-items">
              <div
                  v-for="category in categories.secondary"
                  :key="category.id"
                  class="category-item"
                  :class="{ active: selected.secondary === category.id }"
                  @click="selectCategory('secondary', category.id)"
              >
                {{ category.name }}
                <el-icon
                    class="delete-icon"
                    @click.stop="deleteCategory('secondary', category.id)"
                >
                  <Delete />
                </el-icon>
              </div>
              <div class="category-item add-new" @click="showAddDialog('secondary')">
                <el-icon><Plus /></el-icon>
                添加分类
              </div>
            </div>
          </div>

          <!-- 三级分类 -->
          <div class="tree-level" v-if="selected.secondary">
            <div class="level-title">三级分类（可选）</div>
            <div class="level-items">
              <div
                  v-for="category in categories.tertiary"
                  :key="category.id"
                  class="category-item"
                  :class="{ active: selected.tertiary === category.id }"
                  @click="selectCategory('tertiary', category.id)"
              >
                {{ category.name }}
                <el-icon
                    class="delete-icon"
                    @click.stop="deleteCategory('tertiary', category.id)"
                >
                  <Delete />
                </el-icon>
              </div>
              <div class="category-item add-new" @click="showAddDialog('tertiary')">
                <el-icon><Plus /></el-icon>
                添加分类
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 预览区域 -->
      <div class="preview-section" v-if="taskRecord">
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="输出文件">
            {{ taskRecord.output_name }}
          </el-descriptions-item>
          <el-descriptions-item label="选择路径">
            {{ categoryPath || '请选择分类' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button
          type="primary"
          :loading="submitting"
          :disabled="!canSubmit"
          @click="handleSubmit"
      >
        开始训练
      </el-button>
    </template>

    <!-- 添加分类对话框 -->
    <el-dialog
        v-model="addDialog.visible"
        :title="`添加${getLevelName(addDialog.level)}分类`"
        width="400px"
    >
      <el-form>
        <el-form-item label="分类名称">
          <el-input
              v-model="addDialog.name"
              placeholder="请输入分类名称"
              @keyup.enter="addCategory"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="addCategory">确定</el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Plus, VideoPlay } from '@element-plus/icons-vue'
import api from '@/api'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  videoPath: {
    type: String,
    default: ''
  },
  taskRecord: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'training-complete'])

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 响应式数据
const categories = ref({
  primary: [],
  secondary: [],
  tertiary: []
})

const selected = ref({
  primary: null,
  secondary: null,
  tertiary: null
})

const addDialog = ref({
  visible: false,
  level: '',
  name: ''
})

const submitting = ref(false)
const loading = ref(false)

// 计算属性
const canSubmit = computed(() => {
  return selected.value.primary && selected.value.secondary
})

const categoryPath = computed(() => {
  if (!selected.value.primary) return ''

  const primary = categories.value.primary.find(c => c.id === selected.value.primary)
  if (!primary) return ''

  let path = primary.name

  if (selected.value.secondary) {
    const secondary = categories.value.secondary.find(c => c.id === selected.value.secondary)
    if (secondary) {
      path += ' / ' + secondary.name

      if (selected.value.tertiary) {
        const tertiary = categories.value.tertiary.find(c => c.id === selected.value.tertiary)
        if (tertiary) {
          path += ' / ' + tertiary.name
        }
      }
    }
  }

  return path
})

// 监听对话框打开
watch(visible, async (newVal) => {
  if (newVal) {
    await loadCategories()
  }
})

// 方法
const loadCategories = async () => {
  loading.value = true
  try {
    const result = await api.getCategoryTree()
    if (result.code === 200) {
      // 处理分类树数据，提取一级分类
      categories.value.primary = result.data.map(item => ({
        id: item.id,
        name: item.name,
        level: item.level,
        children: item.children || []
      }))
    }
  } catch (error) {
    ElMessage.error('加载分类失败')
  } finally {
    loading.value = false
  }
}

const selectCategory = async (level, categoryId) => {
  selected.value[level] = categoryId

  if (level === 'primary') {
    // 重置下级分类
    selected.value.secondary = null
    selected.value.tertiary = null
    categories.value.secondary = []
    categories.value.tertiary = []

    // 加载二级分类
    const primary = categories.value.primary.find(c => c.id === categoryId)
    if (primary && primary.children) {
      categories.value.secondary = primary.children.map(item => ({
        id: item.id,
        name: item.name,
        level: item.level,
        children: item.children || []
      }))
    }
  } else if (level === 'secondary') {
    // 重置三级分类
    selected.value.tertiary = null
    categories.value.tertiary = []

    // 加载三级分类
    const secondary = categories.value.secondary.find(c => c.id === categoryId)
    if (secondary && secondary.children) {
      categories.value.tertiary = secondary.children.map(item => ({
        id: item.id,
        name: item.name,
        level: item.level
      }))
    }
  }
}

const showAddDialog = (level) => {
  addDialog.value = {
    visible: true,
    level: level,
    name: ''
  }
}

const getLevelName = (level) => {
  const names = {
    primary: '一级',
    secondary: '二级',
    tertiary: '三级'
  }
  return names[level] || ''
}

const addCategory = async () => {
  if (!addDialog.value.name.trim()) {
    ElMessage.warning('请输入分类名称')
    return
  }

  try {
    let parentId = 0
    let level = 1

    if (addDialog.value.level === 'secondary') {
      parentId = selected.value.primary
      level = 2
    } else if (addDialog.value.level === 'tertiary') {
      parentId = selected.value.secondary
      level = 3
    }

    const result = await api.addCategory(addDialog.value.name, parentId, level)
    if (result.code === 200) {
      ElMessage.success('添加成功')
      addDialog.value.visible = false
      await loadCategories()

      // 如果有选中的上级分类，重新加载该级别的子分类
      if (selected.value.primary) {
        await selectCategory('primary', selected.value.primary)
        if (selected.value.secondary) {
          await selectCategory('secondary', selected.value.secondary)
        }
      }
    }
  } catch (error) {
    ElMessage.error('添加分类失败')
  }
}

const deleteCategory = async (level, categoryId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个分类吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const result = await api.deleteCategory(categoryId)
    if (result.code === 200) {
      ElMessage.success('删除成功')

      // 保存当前选中状态
      const currentSelection = {
        primary: selected.value.primary,
        secondary: selected.value.secondary,
        tertiary: selected.value.tertiary
      }

      // 如果删除的是当前选中的分类，清空选择
      if (selected.value[level] === categoryId) {
        selected.value[level] = null
        if (level === 'primary') {
          selected.value.secondary = null
          selected.value.tertiary = null
        } else if (level === 'secondary') {
          selected.value.tertiary = null
        }
      }

      // 重新加载一级分类
      await loadCategories()

      // 根据删除的级别和当前选择，重新加载对应的子分类
      if (currentSelection.primary) {
        // 重新选择一级分类，这会加载二级分类
        await selectCategory('primary', currentSelection.primary)

        // 如果之前有选中二级分类且删除的不是当前选中的二级分类
        if (currentSelection.secondary && !(level === 'secondary' && selected.value.secondary === null)) {
          // 重新选择二级分类，这会加载三级分类
          await selectCategory('secondary', currentSelection.secondary)
        }
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!canSubmit.value) {
    ElMessage.warning('请至少选择一级和二级分类')
    return
  }

  submitting.value = true
  try {
    // 调用训练API
    const result = await api.startTraining({
      taskId: props.taskRecord.task_id,
      videoPath: props.taskRecord.result_path,
      primaryCategoryId: selected.value.primary,
      secondaryCategoryId: selected.value.secondary,
      tertiaryCategoryId: selected.value.tertiary || 0,
      modelName: props.taskRecord.output_name,
    })

    emit('training-complete', { success: true })
    handleClose()
  } catch (error) {
    console.error('训练失败:', error)
    emit('training-complete', {
      success: false,
      message: error.message
    })
  } finally {
    submitting.value = false
  }
}

const handleClose = () => {
  visible.value = false
  // 重置状态
  selected.value = {
    primary: null,
    secondary: null,
    tertiary: null
  }
}
</script>

<style lang="scss" scoped>
.category-selector {
  .selector-section {
    margin-bottom: 20px;

    .section-title {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 15px;
    }

    .category-tree {
      .tree-level {
        margin-bottom: 20px;

        .level-title {
          font-size: 14px;
          color: #606266;
          margin-bottom: 10px;
        }

        .level-items {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;

          .category-item {
            position: relative;
            padding: 8px 16px;
            background: #f5f7fa;
            border: 1px solid #e4e7ed;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;

            &:hover {
              background: #e6f7ff;
              border-color: #91d5ff;

              .delete-icon {
                opacity: 1;
              }
            }

            &.active {
              background: #409eff;
              color: white;
              border-color: #409eff;
            }

            &.add-new {
              border-style: dashed;
              color: #409eff;
              display: flex;
              align-items: center;
              gap: 5px;

              &:hover {
                background: #f0f9ff;
                border-color: #409eff;
              }
            }

            .delete-icon {
              position: absolute;
              top: -5px;
              right: -5px;
              width: 20px;
              height: 20px;
              background: #f56c6c;
              color: white;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              opacity: 0;
              transition: opacity 0.3s;
              font-size: 12px;

              &:hover {
                background: #f23030;
              }
            }
          }
        }
      }
    }
  }

  .preview-section {
    border-top: 1px solid #ebeef5;
    padding-top: 20px;
  }
}
</style>